﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using OpenNETCF.MTConnect;
using System.Threading;
using System.Xml.Linq;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace Okuma
{
    public class OkumaAdapter : HostedAdapterBase, IHostedAdapter, IDisposable
    {
        private MachineDevice m_device;
        private OkumaConfiguration m_config;

        public OkumaAdapter()
        {
            // TODO: load config
            var configDoc = XDocument.Load(GetConfigFilePath());
            m_config = OkumaConfiguration.FromXml(configDoc);

            m_refreshPeriod = m_config.RefreshPeriod;
        }

        private string GetConfigFilePath()
        {
            var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            if (path.StartsWith("file:\\")) path = path.Substring(6);
            return Path.Combine(path, "OkumaConfig.xml");
        }

        public override IHostedDevice HostedDevice
        {
            get { return m_device; }
        }

        public override void BeforeLoad()
        {
            base.BeforeLoad();

            // determine our machine info

            try
            {
                m_device = new MachineDevice(this, m_config);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        protected override void OnPublish()
        {
            base.OnPublish();
            m_device.OnRefreshTick();
            UpdateProperties();
        }
    }
}
